package com.xxcloud.service.folder.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.base.Preconditions;
import com.xxcloud.common.utils.DateTimeUtil8;
import com.xxcloud.dao.dto.xxcloud.Folder;
import com.xxcloud.dao.dto.xxcloud.FolderExample;
import com.xxcloud.dao.mapper.xxcloud.FolderMapper;
import com.xxcloud.model.exception.folder.FolderException;
import com.xxcloud.model.web.ListResult;
import com.xxcloud.model.web.folder.dto.FolderDTO;
import com.xxcloud.model.web.folder.vo.FolderVO;
import com.xxcloud.service.folder.IFolderService;

/**
 * Created by chenbingwen on 19/10/28.
 */
@Service("folderService")
public class FolderServiceImpl extends AbstractFolderService implements IFolderService {

    @Autowired
    private FolderMapper folderMapper;

    @Override
    public ListResult<FolderVO> listFolderVO() {
        ListResult<FolderVO> result = new ListResult<>();
        FolderExample example = new FolderExample();
        int total = folderMapper.countByExample(example);
        if (total > 0) {
            List<Folder> folders = folderMapper.selectByExample(example);
            result.setResult(convert2FolderVOS(folders));
        }
        result.setTotal(total);
        return result;
    }

    @Override
    public boolean upsertFolder(long operatorId, FolderDTO dto) throws FolderException {
        Preconditions.checkNotNull(dto);
        boolean result = false;
        Folder folder = convert2Folder(dto);
        Long id = dto.getId();
        if (id != null && id > 0) {
            Folder dbFolder = getFolderById(id);
            if (dbFolder == null) {
                throw new FolderException(FolderException.FOLDER_NOT_EXISTS);
            }
            result = updateFolder(operatorId, folder);
        } else {
            result = insertFolder(operatorId, folder);
        }
        return result;
    }

    @Override
    public Folder getFolderById(long id) {
        return folderMapper.selectByPrimaryKey(id);
    }

    private boolean insertFolder(long operatorId, Folder folder) {
        Date now = DateTimeUtil8.getCurrentDate();
        folder.setCreateTime(now);
        folder.setUpdateTime(now);
        folder.setCreateUserId(operatorId);
        folder.setUpdateUserId(operatorId);
        return folderMapper.insertSelective(folder) > 0;
    }

    private boolean updateFolder(long operatorId, Folder folder) {
        Long id = folder.getId();
        if (id == null || id <= 0) {
            return false;
        }
        Date now = DateTimeUtil8.getCurrentDate();
        folder.setUpdateTime(now);
        folder.setUpdateUserId(operatorId);
        return folderMapper.updateByPrimaryKeySelective(folder) > 0;
    }

}
